package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;


/**
 * 11-请求对象获取请求参数
 */
@WebServlet("/demo15")
public class Demo15Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //getParameter : 根据指定请求参数名称获取值
        String username = request.getParameter("username");
        System.out.println("username = " + username);
        String password = request.getParameter("password");
        System.out.println("password = " + password);

        //getParameterValues : 根据指定请求参数名称获取一组值(多选)
        String username2 = request.getParameterValues("username")[0];
        System.out.println("username2 = " + username2);
        String password2 = request.getParameterValues("password")[0];
        System.out.println("password2 = " + password2);

        //getParameterNames : 获取所有请求参数名称
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            String parameterValue = request.getParameter(parameterName);
            System.out.println("parameterName = " + parameterName + " , parameterValue = " + parameterValue);
        }

        //getParameterMap : 获取请求参数，并将其封装成map(键=参数名,值=一组参数值)
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entrySet = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entrySet) {
            String parameterName = entry.getKey();
            String[] parameterValues = entry.getValue();
            System.out.println("parameterName = " + parameterName + " , parameterValues = " + Arrays.toString(parameterValues));

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
